package com.roads.web.controller.common;

import com.roads.common.config.ExcelTemplateConfig;
import com.roads.common.config.MasterConfig;
import com.roads.common.constant.Constants;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.domain.FileEntity;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.StringUtils;
import com.roads.common.utils.file.FileUploadUtils;
import com.roads.common.utils.file.FileUtils;
import com.roads.common.utils.file.MimeTypeUtils;
import com.roads.framework.config.ServerConfig;
import com.roads.system.domain.SysAnnexFile;
import com.roads.system.service.ISysAnnexFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author nhp
 */
@RestController
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysAnnexFileService annexFileService;

    @Autowired
    private ExcelTemplateConfig excelTemplateConfig;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = MasterConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = MasterConfig.getUploadAnnexPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 附件上传
     *
     * @param file 文件
     * @param uuid uuid
     * @param menuType 菜单类型
     * @return 结果
     * @throws Exception 异常
     */
    @PostMapping("/common/upload/annex")
    public AjaxResult uploadAnnexFile(MultipartFile file, String uuid, Integer menuType) throws Exception {
        System.out.println(uuid);
        try{
            String annexPath = MasterConfig.getUploadAnnexPath() + "/" + menuType + "/" + uuid;
            String fileName = file.getOriginalFilename();
            FileEntity fileEntity = FileUploadUtils.annexUpload(annexPath, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            String filePath = fileEntity.getFilePath();
            String rename = filePath.substring(filePath.lastIndexOf("/") + 1);
            SysAnnexFile sysAnnexFile = new SysAnnexFile();
            sysAnnexFile.setRefilename(rename);
            sysAnnexFile.setFileName(fileName);
            if (fileEntity.getImage()) {
                sysAnnexFile.setIsImg(Constants.YES);
            } else {
                sysAnnexFile.setIsImg(Constants.NO);
            }
            sysAnnexFile.setFilePath(filePath);
            sysAnnexFile.setUuid(uuid);
            sysAnnexFile.setMenuType(menuType);
            sysAnnexFile.setCreateBy(SecurityUtils.getUsername());
            annexFileService.insert(sysAnnexFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success();
    }

    /**
     * 附件列表
     *
     * @param uuid uuid
     * @return 附件集合
     */
    @GetMapping("common/annexList")
    public AjaxResult annexList(String uuid) {
        SysAnnexFile search  = new SysAnnexFile();
        search.setUuid(uuid);
        List<SysAnnexFile> list = annexFileService.selectModelList(search);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("list", list);
        ajaxResult.put("annexCount", list.size());
        return ajaxResult;
    }

    /**
     * 附件下载
     *
     * @param fileId 文件ID
     * @param response 响应
     * @param request 请求
     */
    @GetMapping("common/downloadAnnexFile")
    public void downloadAnnexFile(Long fileId, HttpServletResponse response, HttpServletRequest request) {
        try {
            SysAnnexFile file = annexFileService.getModelById(fileId);
            String fileName = file.getFileName();
            String filePath = MasterConfig.getUploadAnnexPath() + "/" + file.getMenuType() + "/" + file.getUuid() + "/" + file.getRefilename();

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("common/deleteAnnexFile")
    public AjaxResult deleteAnnexFile(Long fileId) {
        SysAnnexFile file = annexFileService.getModelById(fileId);
        String filePath = MasterConfig.getUploadAnnexPath() + "/" + file.getMenuType() + "/" + file.getUuid() + "/" + file.getRefilename();
        FileUtils.deleteFile(filePath);
        annexFileService.delete(fileId);
        return AjaxResult.success();
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = MasterConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用模板下载
     *
     * @param key 文件key
     */
    @GetMapping("common/downloadTemplate")
    public void downloadTemplate(String key, HttpServletResponse response, HttpServletRequest request) {
        try {
            Map<String, String> names = excelTemplateConfig.getNames();
            Map<String, String> templates = excelTemplateConfig.getTemplates();
            String classpath = ResourceUtils.getURL("classpath:").getPath();
            String fileName = names.get(key);
            String templateFilePath = templates.get(key);
            String filePath = classpath + templateFilePath;
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("multipart/form-data");
//            response.setHeader("Content-Disposition",
//                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
//            FileUtils.writeBytes(filePath, response.getOutputStream());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载模板失败", e);
        }
    }
}
